﻿using MediatR;
using NPOI.XSSF.UserModel;
using ProductManagement.Applcation.Command;
using ProductManagement.Domain.Dtos;
using ProductManagement.Domain.ProductsDomain;
using ProductManagement.Infrstructre.Interface;

namespace ProductManagement.Applcation.CommandHanlers
{
    /// <summary>
    /// 产品分类树形显示
    /// </summary>
    public class ProductsTypeSelectCommandHandlers : IRequestHandler<ProductsTypeSelectCommand, List<ProductsTypeSelectDto>>
    {
        protected readonly InterfaceProductsTypeRepository repository;

        public ProductsTypeSelectCommandHandlers(InterfaceProductsTypeRepository repository)
        {
            this.repository = repository;
        }

        public async Task<List<ProductsTypeSelectDto>> Handle(ProductsTypeSelectCommand request, CancellationToken cancellationToken)
        {
            List<ProductType> categories = (await repository.GetAll()).ToList();
            List<ProductsTypeSelectDto> treeCategories = BuildTree(categories, request.id);
            return treeCategories;
        }
        static List<ProductsTypeSelectDto> BuildTree(List<ProductType> categories, int parentId)
        {
            return categories
                .Where(c => c.PFatherId == parentId && c.IsDel == false)
                .Select(c => new ProductsTypeSelectDto
                {
                    value = c.ProductTypeId,
                    label = c.PTClass,
                    children = BuildTree(categories, c.ProductTypeId) // 递归构建子分类
                })
                .ToList();
        }


    }
}
